const WebSocket = require('ws');
const dao = require('../dao/dao');
const dao_houtai = require('../dao/dao_houtai');

function startPushBigWin(wss) {
    console.log('📢[推送服务] 启动定时广播');

    const pushOnce = async () => {
        try {
            const gameList = await dao_houtai.getGameInfo();
            if (!Array.isArray(gameList) || gameList.length === 0) {
                console.warn('[推送服务] 未找到可用游戏数据');
                return;
            }

            const randomGame = gameList[Math.floor(Math.random() * gameList.length)];
            const username = generateRandomUsername();
            const multiple = generateRandomMultiple();
            const headId = generateRandomHeadId();

            const data = JSON.stringify({
                action: 'tuisong',
                data: {
                    "name": username,
                    "multiple": multiple,
                    "gameId": randomGame.id,
                    "gameName": randomGame.name,
                    "headId": headId
                },

            });

            wss.clients.forEach(client => {
                if (client.readyState === WebSocket.OPEN) {
                    client.send(data);
                }
            });

            // console.log('[推送服务] 已推送:', data);
        } catch (err) {
            console.error('[推送服务] 出错:', err);
        } finally {
            setTimeout(pushOnce, getRandomDelay());
        }
    };

    // 启动第一次推送
    setTimeout(pushOnce, getRandomDelay());
}


// 随机生成用户名，如：A***Z
function generateRandomUsername() {
    const randomUpperChar = () => String.fromCharCode(65 + Math.floor(Math.random() * 26)); // A-Z
    const randomLowerChar = () => String.fromCharCode(97 + Math.floor(Math.random() * 26)); // a-z
    const starsCount = 2 + Math.floor(Math.random() * 3); // 2-4 个 *

    const firstLetter = randomUpperChar();    // 首字母大写
    const secondLetter = randomLowerChar();   // 第二个字母小写
    const lastTwoLetters = randomLowerChar() + randomLowerChar();  // 后面两个小写字母

    return firstLetter + secondLetter + '*'.repeat(starsCount) + lastTwoLetters;
}

// 生成 100~1000 的随机倍数
function generateRandomMultiple() {
    return Math.floor(Math.random() * 901) + 100;
}

// 生成 5-10 秒的随机间隔（毫秒）
function getRandomDelay() {
    return (5 + Math.random() * 5) * 1000;
}

// 生成随机 1- 21 的头像id
function generateRandomHeadId() {
    return Math.floor(Math.random() * 21) + 1;
}


module.exports = { startPushBigWin };